<template>
  <div>
    <iframe
      ref="iframe"
      :src="iframeSrc"
      frameborder="0"
      width="100%"
      :height="iframeHeight"
      v-loading="iframeLoad"
    ></iframe>
  </div>
</template>

<script>
  import { repost, rePostUpload } from '@/api/driverAdapt/driverAdapt'
  let that
  export default {
    name: 'index',
    // dicts:["driver_adapt_url"],
    data(){
      return{
        ip:"8.134.156.156",
        iframeSrc:null,
        iframeHeight:window.innerHeight-90,
        iframeLoad:true
      }
    },
    beforeMount(){
      that = this
      this.getDicts("driver_adapt_url").then(res=>{
        let driverAdaptUrl = res.data[0].dictValue
        that.iframeSrc = driverAdaptUrl
        let pattern = /\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}/g
        that.ip = driverAdaptUrl.match(pattern)[0]
      })
    },
    mounted() {
      that = this
      // 动态获取ip地址，可以在字典管理配置
      const mapFrame = that.$refs.iframe
      const iframeWin = mapFrame.contentWindow
      this.$nextTick(() => {
        if (mapFrame.attachEvent) {
          // eslint-disable-next-line
          mapFrame.attachEvent('onload', function() {
            console.log("mapFrame.onload1")
            // iframeWin.postMessage({},'*')
            that.iframeLoad = false
          })
        } else {
          window.onmessage = function(e) {
            let origin = e.origin
            console.log("receive msg from "+ origin);
            let flag = origin.indexOf(that.ip)>1
            if (flag){
              console.log("iframeWin.onmessage:",e);
              if (e.data.RequestUrl.includes("/files/upload")){
                // 文件上传接口，调用专用接口
                rePostUpload(e.data).then(res=>{
                  console.log("rePostUpload>>>>",res)
                  iframeWin.postMessage(res.data,'*')
                }).catch(errMsg=>{
                  console.error(errMsg);
                })
              }else {
                repost(e.data).then(res=>{
                  console.log("rePost>>>>",res)
                  iframeWin.postMessage(res.data,'*')
                }).catch(errMsg=>{
                  console.error(errMsg);
                })
              }
            }
          }
          mapFrame.onload = function() {
            console.log("mapFrame.onload2")
            that.iframeLoad = false
          };
        }
      })
    }
  }
</script>

<style scoped>

</style>
